import React, { useState, useMemo,useRef,useEffect } from 'react';
import { Button,Tag,Empty,Table,message } from 'antd';
import {overdueTasksColumns,estimationColumns,commonColumns} from './column'
import { isNotYunXiaoNull } from "./utils";
import {
    findTasksToTestThisWeek,
    findTasksToTestToday,
    findTasksToDeployToday,
    findTasksToDeployWeek,
    findTasksExceedingTestingTime,
    findTasksExceedingDeploymentTime,
    findTasksNotPredictedTime,
    exceedTestTime,
    exceedDeployTime,
    isAfterDevelopment,
    convertWorkSaturation,
    capturePage,
    calCompletion
  } from "./utils";
import { Task } from "./types";
import TagComponent from "./TagComponent";
import { TAG_CONFIG } from "./enum";

  // 计算行样式的函数
const getRowClassName = (record: Task) => {
  if (exceedDeployTime(record)) {
    return "red-row"; // 超出测试完成时间，变红
  }
    if (exceedTestTime(record)) {
      return "yellow-row"; // 超出提测时间，变黄
    }
 
    return "";
  };
 
/*
 * @Author: tangyuhui 317972442@qq.com
 * @Date: 2024-09-03 11:51:06
 * @LastEditors: tangyuhui 317972442@qq.com
 * @LastEditTime: 2024-09-03 22:06:26
 */
interface IProps {
    elementsData: Task[],
    getElements: () => void
}
const Board=({elementsData,getElements}:IProps)=>{
    const [fullElements, setFullElements] = useState<Task[]>(elementsData);
    const [selectedDetails, setSelectedDetails] = useState<Task[]>();
    const [selectedPerson, setSelectedPerson] = useState<string>('');
    const screenshotRef = useRef<HTMLDivElement>(null);
    const [selectedTag, setSelectedTag] = useState<string>(TAG_CONFIG.ALL); // 用来跟踪选中的标签

    // 使用 useEffect 来监听 elementsData 的变化
    useEffect(() => {
        setFullElements(elementsData);
    }, [elementsData]);
    // 使用 useMemo 进行性能优化
    const workSaturation = useMemo(() => convertWorkSaturation(elementsData), [elementsData]);

    const tasksToTestThisWeek = useMemo(() => findTasksToTestThisWeek(elementsData), [elementsData]);

    const tasksToTestToday = useMemo(() => findTasksToTestToday(elementsData), [elementsData]);

    const tasksToDeployToday = useMemo(() => findTasksToDeployToday(elementsData), [elementsData]);

    const tasksToDeployThisWeek = useMemo(() => findTasksToDeployWeek(elementsData), [elementsData]);

    const sprintCompletion = useMemo(() => calCompletion(elementsData), [elementsData]);
    const {finishTask,completion} = sprintCompletion;

    const { noFront, noBackend, noTest, noDevelop, noTestFinishTime,noPublishTime,notFinished} = useMemo(
      () => findTasksNotPredictedTime(elementsData),
      [elementsData]
    );

    const tasksNotFrontPredictedTime = noFront;
    const tasksNotBackPredictedTime = noBackend;
    const tasksNotTestPredictedTime = noTest;
    const tasksNotDevelop = noDevelop;
    const tasksNotTestFinishTime = noTestFinishTime;
    const tasksNotPublishTime = noPublishTime;
    const summaryStat = useMemo(() =>elementsData.filter(item=>!isNotYunXiaoNull(item.tag) || !item.tag.includes('忽略')), [elementsData]);
    console.log(summaryStat)
    const tasksExceedingTestingTime = useMemo(
      () => findTasksExceedingTestingTime(elementsData),
      [elementsData]
    );

    const tasksExceedingDeploymentTime = useMemo(
      () => findTasksExceedingDeploymentTime(elementsData),
      [elementsData]
    );
  
    const handleTagClick = (tag: string, data: Task[]) => {
        setSelectedTag(tag); // 更新选中的标签
        setFullElements(data); // 设置对应的数据
      };

  // 拷贝关键信息
  const copyKeys = (): string => {
    // 使用 map 方法遍历数组并格式化输出每个对象的指定字段
    const data = elementsData.map((task:Task,index) => {
        return `${task.task}, ${task.testingTime}, ${task.onlineTime},${task.frontEndLeader},${task.backEndLeader},${task.testLeader}`;
      })
      .join("\n");
      copyToClipboard(data)
    return data;
  };
  const copyToClipboard = (text: string): void => {
    navigator.clipboard.writeText(text).then(() => {
      message &&message.success('已复制到剪贴板')
    }).catch(err => {
      message && message.error('复制失败')
    });
  }

  const workHoursColumns = [
    {
      title: "人员",
      dataIndex: "name",
      ellipsis: {
        showTitle: true,
      },
    },
    {
      title: "工时（人/日）",
      dataIndex: "workHours",
    },
    {
      title: "任务完成度",
      dataIndex: "taskList",
      render:(taskList:Task[],record:any)=>{
        const total = taskList && taskList.length
        // 统计已完成、已发布的数量
        const completed = taskList && taskList.filter(item=>isAfterDevelopment(item,record)).length
        return (
          <a
          href="#"
          onClick={(e) => {
            e.preventDefault();
            handleCellClick(taskList,record.name||'');
          }}
          style={{ cursor: 'pointer' }}
        >
          {completed}/{total}
        </a>
        )
      }
  
    },
  ];

  const handleCellClick=(taskList:Task[],name:string)=>{
    setSelectedDetails(taskList);
    setSelectedPerson(name)
  }

  const renderTag = ()=>{
    const tagConfigs = [
      { label: TAG_CONFIG.ALL, data: elementsData },
      { label: TAG_CONFIG.STAT, data: summaryStat },
      { label: TAG_CONFIG.FINISHED, data: finishTask },
      { label: TAG_CONFIG.NOT_FINISHED, data: notFinished }, // 假设这是未完成的标识
      { label: TAG_CONFIG.NO_TEST_FINISH_DATE, data: tasksNotTestFinishTime },
      { label: TAG_CONFIG.NO_DEPLOY_DATE, data: tasksNotPublishTime },

    ];
    
    const renderTags = [];
    for (let i = 0; i < tagConfigs.length; i++) {
      const tagConfig = tagConfigs[i];
      renderTags.push(
        <TagComponent
          key={tagConfig.label} // 添加 key 保证每个组件唯一
          label={tagConfig.label}
          isActive={selectedTag === tagConfig.label}
          onClick={() => handleTagClick(tagConfig.label, tagConfig.data)}
        />
      );
    }
    return renderTags;
  }
    return (<>
    <Button  type="primary" onClick={getElements}>刷新数据</Button>
        <Button
           className="ml-10"
           type="primary"
           onClick={()=>{screenshotRef.current&&capturePage(screenshotRef.current)}}
           data-html2canvas-ignore
         >
           截图
         </Button>
         <Button
           className="ml-10"
           type="primary"
           onClick={copyKeys}
           data-html2canvas-ignore
         >
           拷贝信息
         </Button>
         <div className="mt-10">
           {elementsData && elementsData.length > 0 ? (
             <div className="pd-10" ref={screenshotRef}>
               <h4 className="mt-20">工时统计</h4>
               <Table
                 pagination={false}
                 size="small"
                 dataSource={workSaturation}
                 columns={workHoursColumns}
               />
               <div>
              <div className="mt-20">
            { workSaturation&& workSaturation.map(item=><Tag color="orange" className="cursor" onClick={()=>handleCellClick(item.taskList,item.name)}>{item.name}</Tag>)}
             </div> 
               {selectedDetails && selectedDetails.length > 0 && (
           <div style={{ marginTop: 20 }}>
             <h4>{selectedPerson}-任务详情</h4>
             <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={selectedDetails}
                 columns={estimationColumns}
               />
                    {/* <ul>
               {selectedDetails.map((detail, index) => (
                 <li key={index}>{detail.task}({detail.status})</li>
               ))}
             </ul> */}
           </div>
         )}
               </div>
               <h4 className="mt-20">超出提测时间</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksExceedingTestingTime}
                 columns={commonColumns}
               />
               <h4 className="mt-20">超出发布时间</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksExceedingDeploymentTime}
                 columns={overdueTasksColumns}
               />
               <h4 className="mt-20">预计今天提测</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksToTestToday}
                 columns={commonColumns}
               />
               <h4 className="mt-20">预计今天发布</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksToDeployToday}
                 columns={commonColumns}
               />
               <h4 className="mt-20">预计本周提测</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksToTestThisWeek}
                 columns={commonColumns}
               />
               <h4 className="mt-20">预计本周发布</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksToDeployThisWeek}
                 columns={commonColumns}
               />
               <h4 className="mt-20">前端未估时</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksNotFrontPredictedTime}
                 columns={estimationColumns}
               />
               <h4 className="mt-20">后端未估时</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksNotBackPredictedTime}
                 columns={estimationColumns}
               />
               <h4 className="mt-20">未安排开发人员</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksNotDevelop}
                 columns={commonColumns}
               />
               <h4 className="mt-20">测试未估时</h4>
               <Table
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={tasksNotTestPredictedTime}
                 columns={estimationColumns}
               />
               <h4 className="mt-20"><span className='mr-10'>本迭代任务</span><Tag className="ml-10" color="processing"> 已完成{finishTask.length}/{elementsData.length},完成率：{completion}%</Tag></h4>
               <Table
               className='mt-10'
                 pagination={false}
                 size="small"
                 rowClassName={getRowClassName}
                 dataSource={fullElements}
                 columns={commonColumns}
               />
               <div className='mt-10'>
                {renderTag()}
               </div>
             </div>
           ) : (
             <Empty />
           )}
         </div>
    </> )
}

export default Board